/* post 请求接收 */
const Koa = require('koa');
const app = new Koa();
app.use(async ( ctx ) =>{
	//当请求GET请求时，显示表单让用户填写
	if (ctx.url === '/' && ctx.method === 'GET') {
		let html = `
			<h1>Koa2 request post demo</h1>
			<form method="POST" action="/">
				<p>userName</p>
				<input type="text" name="userName" /><br/>
				<p>age:</p>
				<input type="text" name="age" /><br/>
				<p>webSite:</p>
				<input type="text" name="webSite" /><br/><br/>
				<button type="submit">submit</button>
			</form>
		`;
		ctx.body = html;
	}else if(ctx.url === '/' && ctx.method === 'POST'){
	//当请求POST请求时
		// ctx.body = '接收到请求';
		let postData = await parsePostData(ctx);
 		ctx.body = postData;
	}else{
	//其他请求显示404
		ctx.body = '<h1>404！</h1>'
	}
});

app.listen(3000, ()=>{
	console.log('[demo] server is starting at port 3000');
})
//解析Node原生POST参数
function parsePostData(ctx){
  return new Promise((resolve,reject)=>{
    try{
        let postdata = "";
        ctx.req.on('data',(data)=>{
            postdata += data
        })
        ctx.req.addListener("end",function(){
        	let parseData = parseQuery( postdata );
            resolve(parseData);
        })
    }catch(error){
        reject(error);
    }
  });
}
//POST字符串解析JSON对象
function parseQuery(queryStr){
	let queryData = {};
	let queryStrList = queryStr.split('&');
	console.log(queryStrList);
	for (let [index,queryStr] of queryStrList.entries() ) {
		let itemList = queryStr.split('=');
		console.log(itemList);
		queryData[itemList[0]] = decodeURIComponent(itemList[1]);
	}
	return queryData;
}